package com.sskj.ws.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sskj.ws.dto.HeartbeatMessage;
import com.sskj.ws.service.IMessageService;
import jakarta.websocket.Session;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class HeartbeatMessageService implements IMessageService<HeartbeatMessage> {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public String getSupportedType() {
        return "heartbeat";
    }

    @Override
    public Class<HeartbeatMessage> getMessageClass() {
        return HeartbeatMessage.class;
    }

    @Override
    public void handle(HeartbeatMessage message, Session session) {
        Map<String, String> resp = new HashMap<>();
        resp.put("type", "pong");
        resp.put("timestamp", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        try {
            String jsonData = objectMapper.writeValueAsString(resp);
            session.getBasicRemote().sendText(jsonData);
        } catch (JsonProcessingException e) {
            log.error("[心跳响应]-序列化异常。异常信息:{}|内容:{}", e.getMessage(), resp);
        } catch (IOException e) {
            log.error("[心跳响应]-发送异常。异常信息:{}", e.getMessage());
        }
    }
}
